package com.xique.door.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.domain.PageResult;
import com.xique.door.bean.domain.Notice;
import com.xique.door.bean.domain.Problem;
import com.xique.door.bean.domain.SysUser;
import com.xique.door.mapper.NoticeMapper;
import com.xique.door.mapper.ProblemMapper;
import com.xique.door.service.INoticeService;
import com.xique.door.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

  @Autowired private ProblemMapper problemMapper;

  @Autowired private ISysUserService sysUserService;

  @Override
  public PageResult getNoticeList(
      Long parkId,
      Integer pageNum,
      Integer pageSize,
      String theme,
      String status,
      String startTime,
      String endTime,
      String userName,
      String exhibitionStatus) {
    QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
    queryWrapper.select(
            "id,park_id,theme,title,notice_type,release_starttime,release_endtime,push,play,status,content,create_time,update_time,create_user,update_user,selection_method,views,number,"
                    + "CASE WHEN release_starttime >= NOW( ) THEN'未开始' "
                    + "WHEN release_starttime <= NOW( ) && release_endtime >= NOW( ) THEN'展示中' "
                    + "WHEN release_starttime <= NOW( ) && release_endtime IS NULL THEN'展示中' "
                    + "WHEN release_endtime <= NOW( ) THEN'已结束' ELSE '未知' END exhibition_status");
    queryWrapper.eq("park_id", parkId);
    queryWrapper.orderByDesc("create_time");
    if (theme != null && !"".equals(theme)) {
      queryWrapper.like("theme", theme);
    }
    if (status != null && !"".equals(status)) {
      queryWrapper.eq("status", status);
    }
    if (startTime != null && !"".equals(startTime) && endTime != null && !"".equals(endTime)) {
      queryWrapper.between("create_time", startTime, endTime);
    }
    if (startTime != null && !"".equals(startTime)) {
      queryWrapper.ge("create_time", startTime);
    }
    if (userName != null && !"".equals(userName)) {
      SysUser sysUser = sysUserService.getSysUser(null, userName);
      if (sysUser != null) {
        queryWrapper.eq("update_user", sysUser.getUserId());
      } else {
        queryWrapper.isNull("update_user");
      }
    }
    if (exhibitionStatus != null && !"".equals(exhibitionStatus)) {
      if (exhibitionStatus.equals("未开始")) {
        queryWrapper.ge("release_starttime", new Date());
      } else if (exhibitionStatus.equals("展示中")) {
        queryWrapper.le("release_starttime", new Date());
        queryWrapper.and(
            wrappers -> wrappers.ge("release_endtime", new Date()).or().isNull("release_endtime"));
      } else if (exhibitionStatus.equals("已结束")) {
        queryWrapper.le("release_endtime", new Date());
      }
    }
    Page<Notice> page = new Page<>();
    page.setCurrent(pageNum);
    page.setSize(pageSize);
    IPage<Notice> list = baseMapper.selectPage(page, queryWrapper);
    List<Notice> lists = list.getRecords();
    if (lists.size() > 0) {
      for (Notice notice : lists) {
        SysUser sysUser = sysUserService.getSysUser(notice.getUpdateUser(), null);
        if (sysUser != null) {
          notice.setUpdateUserName(sysUser.getUserName());
        }
      }
    }
    long totalPages = list.getPages();
    long totalSize = list.getTotal();
    return PageResult.builder()
        .pageNum(pageNum)
        .pageSize(pageSize)
        .totalPages(totalPages)
        .totalSize(totalSize)
        .list(list.getRecords())
        .build();
  }

  @Override
  public Notice getNotice(Long id) {
    Notice notice = baseMapper.selectById(id);
    if (notice != null && notice.getNoticeType().equals("1")) {
      QueryWrapper<Problem> wrapper = new QueryWrapper();
      wrapper.eq("notice_id", notice.getId());
      List<Problem> list = problemMapper.selectList(wrapper);
      if (list != null) {
        notice.setProblemlist(list);
      }
    }
    return notice;
  }

  @Override
  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  public R insertNotice(Notice notice) {
    notice.setCreateTime(new Date());
    notice.setCreateUser(SecurityUtils.getUserId());
    notice.setUpdateUser(SecurityUtils.getUserId());
    notice.setStatus("1");
    notice.setViews(0);
    notice.setNumber(0);
    if (notice.getNoticeType().equals("1") && notice.getSelectionMethod() == null) {
      return R.fail("选择方式为空");
    }
    int rest = baseMapper.insert(notice);
    if (rest > 0) {
      if (notice.getNoticeType().equals("1")) {
        if (notice.getProblemlist() != null && notice.getProblemlist().size() > 0) {
          for (Problem problem : notice.getProblemlist()) {
            problem.setParkId(notice.getParkId());
            problem.setCreateTime(new Date());
            problem.setNoticeId(notice.getId());
            problem.setNumber(0);
            if (problem.getOptionOrder() == null || "".equals(problem.getOptionOrder())) {
              return R.fail("选项顺序为空");
            }
            if (problem.getOptionContent() == null || "".equals(problem.getOptionContent())) {
              return R.fail("选项内容为空");
            }
            problemMapper.insert(problem);
          }
        } else {
          return R.fail("投票方式没有添加选项");
        }
      } else {
        return R.ok(null, "添加成功");
      }
    } else {
      return R.fail("添加失败");
    }
    return R.ok(null, "添加成功");
  }

  public R updateNotice(Notice notice) {
    Notice notices = baseMapper.selectById(notice.getId());
    if (!notices.getNoticeType().equals(notice.getNoticeType())) {
      return R.fail(null, "公告类型不可修改");
    }
    if (!notices.getPush().equals(notice.getPush())) {
      return R.fail(null, "是否推送到公众号不可修改");
    }
    if (!notices.getPlay().equals(notice.getPlay())) {
      return R.fail(null, "跑马灯播放不可修改");
    }
    baseMapper.updateById(notice);
    if (notice.getNoticeType().equals("1")) {
      if (notice.getProblemlist() != null && notice.getProblemlist().size() > 0) {
        for (Problem problem : notice.getProblemlist()) {
          problemMapper.updateById(problem);
        }
      }
    }
    return R.ok(null, "修改成功");
  }

  public R updateStatus(Long id, String status) {
    Notice notice = new Notice();
    notice.setId(id);
    notice.setStatus(status);
    Integer rep = baseMapper.updateById(notice);
    if (rep > 0) {
      return R.ok(null, "修改成功");
    }
    return R.fail(null, "修改失败");
  }
}
